package tk.mybatis.springboot.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import tk.mybatis.springboot.model.TJoiners;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by NightDream on 2017/9/23.
 */
public class GroupUtils {

    public static ArrayList<ArrayList<TJoiners>> group(int group,
                                                            List<TJoiners>  allJoiner) {
        ArrayList<ArrayList<TJoiners>> mapdata = new ArrayList<>();
        // m 每组几人
        int temp = 0;
        int i = 0, j = 0;
        int[][] k = null;
        int[] allpeoples = new int[allJoiner.size()];
        for (i = 0; i < allpeoples.length; i++) {
            allpeoples[i] = i + 1;
        }
        for (j = 0; j < 3; j++) {
            for (i = 0; i < allpeoples.length; i++) {
                int rand1 = (int) (Math.random() * allpeoples.length);
                int rand2 = (int) (Math.random() * allpeoples.length);
                temp = allpeoples[rand1];
                allpeoples[rand1] = allpeoples[rand2];
                allpeoples[rand2] = temp;
            }
        }

        int a = allJoiner.size() / group;// 组数
        int b = allJoiner.size() % group;
        if (b == 0) {
            k = new int[a][group];
            int step = 0;
            for (i = 0; i < a; i++) {
                k[i] = new int[group];
                for (j = 0; j < group; j++) {
                    k[i][j] = allpeoples[step];
                    step++;
                }
            }
        } else {
            // b = b + 1;
            k = new int[a + 1][group];
            int step = 0;
            for (i = 0; i < a; i++) {
                k[i] = new int[group];
                for (j = 0; j < group; j++) {
                    k[i][j] = allpeoples[step];
                    step++;
                }
            }
            k[a] = new int[b];
            for (i = 0; i < k[a].length; i++) {
                k[a][i] = allpeoples[step];
                step++;
            }
        }
        for (int t1 = 0; t1 < k.length; t1++) {
            int[] k2 = k[t1];
            ArrayList<TJoiners> newGroupNums = new ArrayList<>();
            for (int t2 = 0; t2 < k2.length; t2++) {
                newGroupNums.add(allJoiner.get(k2[t2] - 1));
            }
            mapdata.add( newGroupNums);
        }

        return mapdata;
    }
}
